<template>
  <div :style="styleObj">
    <v-chart :options="options" autoresize />
  </div>
</template>

<script>
import store from "@/store/index.js";
import {
  setMessageCallback,
  publishMsg,
  removeMessageCallback,
  checkSpecialId,
} from "@/mqtt";
import { SCADA_MSG } from "@/mqtt/msg.js";
export default {
  name: "WidgetPiechart",
  components: {},
  props: {
    value: Object,
    ispreview: Boolean,
    widgetIndex: Number,
    pageId: String,
  },
  data() {
    return {
      options: {
        title: {
          text: "",
          left: "center",
          textStyle: {
            color: "#fff",
          },
        },
        legend: {
          orient: "vertical",
          left: "left",
          textStyle: {
            color: "#fff",
          },
        },
        color: [],
        series: [
          {
            name: "",
            type: "pie",
            radius: "50%",
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      },
      optionsStyle: {}, // 样式
      optionsData: {}, // 数据
      optionsCollapse: {}, // 图标属性
      optionsSetup: {},
      key: 1,
      chart: null,
      dataSetting: [],
      timePieChart: {},
      legendName: [],
      timer: [],
      dataArr: [],
      dataPeriod: 1,
    };
  },
  computed: {
    styleObj() {
      return {
        position: this.ispreview ? "absolute" : "static",
        width: this.optionsStyle.width + "px",
        height: this.optionsStyle.height + "px",
        left: this.optionsStyle.left + "px",
        top: this.optionsStyle.top + "px",
        background: this.optionsSetup.background,
      };
    },
  },
  watch: {
    value: {
      handler(val) {
        this.optionsStyle = val.position;
        this.optionsData = val.data;
        this.optionsCollapse = val.collapse;
        this.optionsSetup = val.setup;
        this.editorOptions();
      },
      deep: true,
    },
  },
  created() {
    this.initKey();
    this.sliderChange(this.dataPeriod);
  },
  mounted() {
    setMessageCallback(this.onMsg);

    this.optionsStyle = this.value.position;
    this.optionsData = this.value.data;
    this.optionsCollapse = this.value.collapse;
    this.optionsSetup = this.value.setup;
    this.editorOptions();
  },
  destroyed() {
    for (let i = 0; i < 5; i++) {
      if (this.timer[i] != null) {
        clearInterval(this.timer[i]);
        this.timer[i] = null;
      }
    }

    removeMessageCallback(this.onMsg);
  },
  methods: {
    initKey() {
      this.key = Math.trunc(Math.random() * 1000);
    },
    sliderChange(val) {
      let msg = {
        webMsgType: 1022,
        funCode: 6,
        data: {
          id: this.pageId,
          widgetIndex: this.widgetIndex,
          setup: { dataPeriod: val },
        },
      };
      publishMsg(msg);
      store.commit("updateWidget", msg.data);
      this.parseLineSetting(true);
      // this.restartInterval();
    },
    restartInterval() {
      for (let i = 0; i < 5; i++) {
        if (this.timer[i] != null) {
          clearInterval(this.timer[i]);
          this.timer[i] = null;
        }
        if (this.dataSetting[i].dataId) {
          this.timer[i] = setInterval(() => {
            let dataId = this.dataSetting[i].dataId;
            let dataType = this.dataSetting[i].dataSetNameId;
            // console.log("定时器，i=", i, dataId);
            if (dataType != "" && dataId != "") {
              if (this.timePieChart.hasOwnProperty(dataId)) {
                // console.log(store.state.timePieChart, "----1111pppp----");
                this.options.series[0].data = this.timePieChart[dataId][0];
              } else {
                // console.log("还在等待数据...", dataId);
              }
            } else {
              this.options.series[0].data = [];
              clearInterval(this.timer[i]);
              this.timer[i] = null;
              // console.log("无数据，i=", i);
            }
          }, 100);
        }
      }
    },
    // 修改图标options属性
    editorOptions() {
      this.dataPeriod = this.value.setup.dataPeriod
        ? this.value.setup.dataPeriod
        : this.dataPeriod;
      // console.log(this.dataPeriod, "this.dataPeriod");
      this.setOptionsTitle();
      this.setOptionsValue();
      this.setOptionsTooltip();
      this.setOptionsLegend();
      this.setOptionsColor();
      // this.setOptionsData();
      this.parseLineSetting(true);
      this.setOptionsPiechartStyle();
      this.restartInterval();
    },
    // 饼图样式
    setOptionsPiechartStyle() {
      if (this.optionsSetup.piechartStyle == "shixin") {
        this.options.series[0]["radius"] = "50%";
      } else if (this.optionsSetup.piechartStyle == "kongxin") {
        this.options.series[0]["radius"] = ["40%", "70%"];
      } else {
      }
    },
    // 标题设置
    setOptionsTitle() {
      const optionsSetup = this.optionsSetup;
      const title = {};
      title.show = optionsSetup.isNoTitle;
      title.text = optionsSetup.titleText;
      title.left = optionsSetup.textAlign;
      title.textStyle = {
        color: optionsSetup.textColor,
        fontSize: optionsSetup.textFontSize,
        fontWeight: optionsSetup.textFontWeight,
      };
      title.subtext = optionsSetup.subText;
      title.subtextStyle = {
        color: optionsSetup.subTextColor,
        fontWeight: optionsSetup.subTextFontWeight,
        fontSize: optionsSetup.subTextFontSize,
      };
      this.options.title = title;
    },
    // 数值设定
    setOptionsValue() {
      const optionsSetup = this.optionsSetup;
      const series = this.options.series;
      const numberValue = optionsSetup.numberValue ? "{c}" : "";
      const percentage = optionsSetup.percentage ? "({d})%" : "";
      const label = {
        show: optionsSetup.isShow,
        formatter: `{a|{b}：${numberValue} ${percentage}}`,
        rich: {
          a: {
            padding: [-30, 15, -20, 15],
            color: optionsSetup.subTextColor,
            fontSize: optionsSetup.fontSize,
            fontWeight: optionsSetup.fontWeight,
          },
        },
        fontSize: optionsSetup.fontSize,

        fontWeight: optionsSetup.optionsSetup,
      };
      for (const key in series) {
        if (series[key].type == "pie") {
          series[key].label = label;
          series[key].labelLine = { show: optionsSetup.isShow };
        }
      }
    },
    // 提示语设置 tooltip
    setOptionsTooltip() {
      const optionsSetup = this.optionsSetup;
      const tooltip = {
        trigger: "item",
        show: true,
        textStyle: {
          color: optionsSetup.lineColor,
          fontSize: optionsSetup.fontSize,
        },
      };
      this.options.tooltip = tooltip;
    },
    // 图例操作 legend
    setOptionsLegend() {
      const optionsSetup = this.optionsSetup;
      const legend = this.options.legend;
      legend.show = optionsSetup.isShowLegend;
      legend.left = optionsSetup.lateralPosition == "left" ? 0 : "auto";
      legend.right = optionsSetup.lateralPosition == "right" ? 0 : "auto";
      legend.top = optionsSetup.longitudinalPosition == "top" ? 0 : "auto";
      legend.bottom =
        optionsSetup.longitudinalPosition == "bottom" ? 0 : "auto";
      legend.orient = optionsSetup.layoutFront;
      legend.textStyle = {
        color: optionsSetup.lengedColor,
        fontSize: optionsSetup.fontSize,
      };
      legend.itemWidth = optionsSetup.lengedWidth;
    },
    // 图例颜色修改
    setOptionsColor() {
      const optionsSetup = this.optionsSetup;
      const customColor = optionsSetup.customColor;
      if (!customColor) return;
      const arrColor = [];
      for (let i = 0; i < customColor.length; i++) {
        arrColor.push(customColor[i].color);
      }
      this.options.color = arrColor;
      this.options = Object.assign({}, this.options);
      // console.log(this.options, "饼图配置");
    },
    GetDateStr(days) {
      var date = new Date();
      // date.setDate(date.getDate() + days); //获取AddDayCount天后的日期
      date.setHours(date.getHours() - days); //获取AddDayCount小时的日期
      var Y = date.getFullYear();
      var M = date.getMonth() + 1; //获取当前月份的日期
      var D = date.getDate() >= 10 ? date.getDate() : "0" + date.getDate();
      var H = date.getHours() >= 10 ? date.getHours() : "0" + date.getHours(); //获取系统时间
      var m =
        date.getMinutes() >= 10 ? date.getMinutes() : "0" + date.getMinutes(); //分
      var s =
        date.getSeconds() >= 10 ? date.getSeconds() : "0" + date.getSeconds(); //秒
      return Y + "-" + M + "-" + D + " " + H + ":" + m + ":" + s;
    },
    checkDataListIsExist(dataId) {
      if (store.state.timePieChart.hasOwnProperty(dataId)) {
        return true;
      } else {
        return false;
      }
    },
    isMyData(id) {
      let bHasId = false;
      for (let i = 0; i < this.dataSetting.length; i++) {
        if (this.dataSetting[i].dataId == id) {
          bHasId = true;
          break;
        }
      }
      return bHasId;
    },
    //stroe 里面没有对应的数据就会执行该方法 --- 用来查询数据
    reqDataList(dataType, dataId) {
      this.dataArr = [];
      let msg = {
        webMsgType: 1020,
        funCode: 1,
      };
      let obj = {};
      this.$set(obj, "id", dataId);
      switch (dataType) {
        case "yc":
          this.$set(obj, "from", "data-yc");
          break;
        case "ym":
          this.$set(obj, "from", "data-ym");
          break;
        case "task":
          this.$set(obj, "from", "data-task");
          break;
        default:
          return;
      }
      // this.$set(obj, "endTime", "now");
      // this.$set(obj, "beginTime", this.GetDateStr(1));
      // console.log(this.dataPeriod);
      this.$set(obj, "count", this.dataPeriod);
      msg.data = obj;
      // console.log(msg, "查询");
      publishMsg(msg);
      // store.commit("resetTimePieChartData", dataId);
      // this.parseLineSetting(true);

      // console.log("reqDataList:", dataId);
    },
    parseLineSetting(force) {
      if (this.optionsData.dataType === "dynamicData") {
        if (this.optionsData.dynamicData.hasOwnProperty("chartProperties")) {
          this.dataSetting = this.optionsData.dynamicData.chartProperties;
          // console.log(this.dataSetting, "配置项数据");
          this.legendName = [];
          // return;
          for (let i = 0; i < this.dataSetting.length; i++) {
            this.options.series[0].name = "";
            this.options.series[0].data = [];
            let el = this.dataSetting[i];
            // console.log(el, "el----el");
            let dataId = el.dataId;
            let dataType = el.dataSetNameId;
            if (dataType != "" && dataId != "") {
              if (force) {
                this.reqDataList(dataType, dataId);
              } else {
                // console.log(
                //   this.checkDataListIsExist(dataId),
                //   "checkDataListIsExist"
                // );
                if (!this.timePieChart.hasOwnProperty(dataId)) {
                  this.reqDataList(dataType, dataId);
                }
              }
              // this.options.series[0].name = store.state.data[dataId].name;
              // this.legendName.push(store.state.data[dataId].name);
            }
          }
        }
      }
      // console.log("parseLineSetting dataSetting=", this.dataSetting);
      // console.log("parseLineSetting series=", this.options.series);
    },
    //添加饼图数据
    addPieChartData(data) {
      // console.log(data, 'addPie添加饼图数据')
      // console.log(state.timeLineChart.hasOwnProperty(data.id))
      if (!this.timePieChart.hasOwnProperty(data.id)) {
        this.timePieChart[data.id] = [];
      }
      this.timePieChart[data.id].push(data.data);
    },
    removeTimePieChartData(cfg) {
      let id = cfg.id;
      if (this.timePieChart.hasOwnProperty(id)) {
        let length = this.timePieChart[id].length;
        let canRemoveCount = 0;
        if (length > cfg.dataPeriod) {
          canRemoveCount = length - cfg.dataPeriod;
          this.timePieChart[id].splice(0, canRemoveCount);
          // console.log(state.timeBarChart[id])
        }
      }
    },
    onMsg(topic, msg) {
      // console.log("topology onMsg", msg.data);
      switch (msg.webMsgType) {
        case SCADA_MSG.scada_param_dashboard:
          {
            if (msg.funCode == 6) {
              if (checkSpecialId(msg)) {
                console.log("设置显示数据周期个数成功！");
              }
            }
          }
          break;
        case SCADA_MSG.scada_param_data:
          {
            if (msg.funCode == 1) {
              if (msg.retCode != 0) {
                return this.$message.error(msg.retMsg);
              } else {
                let data = msg.data;
                let dataId = data.id;
                let dataList = data.data;
                console.log(dataList, "数据返回值");
                let isReq = this.isMyData(dataId);

                if (isReq) {
                  // console.log(dataId, "------ss------");
                  // store.commit("resetTimePieChartData", dataId);
                  this.timePieChart[dataId] = [];
                  // var dataArr = [];
                  let obj = {};
                  for (let i = 0; i < dataList.length; i++) {
                    let el = this.dataSetting[i];
                    let dataIds = el.dataId;
                    let dataType = el.dataSetNameId;
                    // console.log(dataId, dataType, "datatype");
                    if (dataType != "" && dataIds != "") {
                      this.dataArr.push({
                        value: dataList[i].value,
                        name: dataType,
                      });
                    }
                    // obj.data.value = [];
                    // let datetime = dataList[i].datetime;
                    // obj.data.value.push(dataList[i].value);
                    obj.id = dataId;
                    obj.data = this.dataArr;
                    // console.log(obj, "组织的饼图数据");
                    // store.commit("addPieChartData", obj);
                    this.addPieChartData(obj);
                  }

                  // this.dataArr = [];
                  let cfg = { id: dataId, dataPeriod: this.dataPeriod };
                  // store.commit("removeTimePieChartData", cfg);
                  this.removeTimePieChartData(cfg);
                }
              }
            }
          }
          break;
        case SCADA_MSG.scada_param_yc:
          {
            switch (msg.funCode) {
              case 2:
                {
                  let dataList = msg.data;
                  // console.log(dataList);
                  for (let i = 0; i < dataList.length; i++) {
                    let data = dataList[i];
                    let dataId = data.id;
                    let value = data.value;
                    let datetime = data.update_time;
                    if (this.timePieChart.hasOwnProperty(dataId)) {
                      let obj = {};
                      obj.id = dataId;
                      obj.data = {};
                      obj.data.value = [];
                      obj.data.value.push(datetime);
                      obj.data.value.push(value);
                      // console.log(obj);
                      this.addPieChartData(obj);
                    }
                    if (this.isMyData(dataId)) {
                      // console.log(this.isMyData(dataId));
                      let cfg = { id: dataId, dataPeriod: this.dataPeriod };
                      this.removeTimePieChartData(cfg);
                      // store.commit("removeTimeLineChartData", cfg);
                    }
                  }
                }
                break;
            }
          }
          break;
        case SCADA_MSG.scada_param_ym:
          {
            switch (msg.funCode) {
              case 2:
                {
                  let dataList = msg.data;
                  for (let i = 0; i < dataList.length; i++) {
                    let data = dataList[i];
                    let dataId = data.id;
                    let value = data.value;
                    let datetime = data.update_time;
                    if (this.timePieChart.hasOwnProperty(dataId)) {
                      let obj = {};
                      obj.id = dataId;
                      obj.data = {};
                      obj.data.value = [];
                      obj.data.value.push(datetime);
                      obj.data.value.push(value);
                      this.addPieChartData(obj);
                    }
                    if (this.isMyData(dataId)) {
                      let cfg = { id: dataId, dataPeriod: this.dataPeriod };
                      this.removeTimePieChartData(cfg);
                    }
                  }
                }
                break;
            }
          }
          break;
        case SCADA_MSG.scada_param_task:
          {
            switch (msg.funCode) {
              case 4:
                {
                  let data = msg.data;
                  let dataId = data.id;
                  let value = data.value;
                  let datetime = data.update_time;
                  if (this.timePieChart.hasOwnProperty(dataId)) {
                    let obj = {};
                    obj.id = dataId;
                    obj.data = {};
                    obj.data.value = [];
                    obj.data.value.push(datetime);
                    obj.data.value.push(value);
                    this.addPieChartData(obj);
                  }
                  if (this.isMyData(dataId)) {
                    let cfg = { id: dataId, dataPeriod: this.dataPeriod };
                    this.removeTimePieChartData(cfg);
                  }
                }
                break;
            }
          }
          break;
        default:
          break;
      }
    },
    setOptionsData() {
      const optionsData = this.optionsData; // 数据类型 静态 or 动态
      optionsData.dataType == "staticData"
        ? this.staticDataFn(optionsData.staticData)
        : this.dynamicDataFn(optionsData.dynamicData, optionsData.refreshTime);
    },
    staticDataFn(val) {
      const staticData = typeof val == "string" ? JSON.parse(val) : val;
      for (const key in this.options.series) {
        if (this.options.series[key].type == "pie") {
          this.options.series[key].data = staticData;
        }
      }
    },
    dynamicDataFn(val, refreshTime) {
      if (!val) return;
      if (this.ispreview) {
        this.getEchartData(val);
        this.flagInter = setInterval(() => {
          this.getEchartData(val);
        }, refreshTime);
      } else {
        this.getEchartData(val);
      }
    },
    getEchartData(val) {
      const data = this.queryEchartsData(val);
      data.then((res) => {
        this.renderingFn(res);
      });
    },
    renderingFn(val) {
      for (const key in this.options.series) {
        if (this.options.series[key].type == "pie") {
          this.options.series[key].data = val;
        }
      }
    },
  },
};
</script>

<style scoped lang="scss">
.echarts {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style>
